#include "ezfb_device.h"
#include "ezfb_includes.h"
#include "ezfb_types.h"

int ezfb_init(struct ezfb* fb, HWND wnd_handle) 
{
	DDCAPS dd_caps ; 
	DDCAPS dd_hel_caps ; 

	// init fb value 
	fb->vga_ptr = NULL ; 
	fb->dd_ptr = NULL ;  
	fb->dds_ptr = NULL ; 
	fb->scr_width = 0 ; 
	fb->scr_height = 0 ; 
	fb->scr_bpp = 0 ; 

	// create direct draw object
	fb->res_handle = DirectDrawCreate(NULL, &fb->dd_ptr, NULL);
	if (fb->res_handle != DD_OK)
		return EZFB_FAIL_CREATE_DD ; 

	// Get exclusive mode
	fb->res_handle = (fb->dd_ptr)->SetCooperativeLevel(wnd_handle, DDSCL_FULLSCREEN);
	if (fb->res_handle != DD_OK)
		return EZFB_FAIL_SET_FULLSCREEN ; 

	// make sure the direct draw is valid
	(fb->dd_ptr)->GetCaps(&dd_caps, &dd_hel_caps) ;
	if (!(dd_caps.ddsCaps.dwCaps & DDSCAPS_VALID))
		return EZFB_FAIL_GET_DD_INFO ; 



	// create the main framebuffer surface
	memset(&(fb->dds_desc), 0, sizeof(fb->dds_desc)) ;
	(fb->dds_desc).dwSize = sizeof(fb->dds_desc) ;
	(fb->dds_desc).dwFlags = DDSD_CAPS ;
	(fb->dds_desc).ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE ; 
	fb->res_handle = (fb->dd_ptr)->CreateSurface(&(fb->dds_desc), &(fb->dds_ptr), NULL) ;
	if (fb->res_handle != DD_OK)
		return EZFB_FAIL_CREATE_DDS ; 

	if(EZFB_LOCK(fb) != DD_OK) return EZFB_FALSE ;
	// save screen necessary params 
	fb->scr_height = fb->dds_desc.dwHeight ; 
	fb->scr_width = fb->dds_desc.dwWidth ; 
	fb->scr_bpp = fb->dds_desc.ddpfPixelFormat.dwRGBBitCount ;
	EZFB_UNLOCK(fb) ; 

	return EZFB_TRUE ; 	
}


int ezfb_clear_screen(struct ezfb* fb)
{
	if(EZFB_LOCK(fb) != DD_OK) return EZFB_FALSE ;
	EZFB_MAP(fb) ;
	int bytes_need = (int)(fb->scr_bpp / 8) ; 
	bytes_need = (bytes_need > 0) ? bytes_need : 1 ; 
	bytes_need *= fb->scr_width ; 
	bytes_need *= fb->scr_height ; 
	memset(fb->vga_ptr, 0x00, bytes_need) ;  
   // set whole screen black 
   EZFB_UNLOCK(fb) ; 
   return EZFB_TRUE ; 
}

int ezfb_release(struct ezfb* fb)
{
	if(fb->dds_ptr != NULL) {
		(fb->dds_ptr)->Release() ; 
		fb->dds_ptr = NULL ; 
	}

	if(fb->dd_ptr != NULL) {
		(fb->dd_ptr)->Release() ; 
		fb->dd_ptr = NULL ; 
	}
	return EZFB_TRUE ; 
}


